//
//  DetailedItemViewController.m
//  FMS
//
//  Created by Steven on 10/15/13.
//  Copyright (c) 2013 QGSVN. All rights reserved.
//

#import "DetailedItemViewController.h"
#import "AddNewItemViewController.h"
#import "ScheduleInspectionViewController.h"
#import "BuildingMgmtViewController.h"
#import "MaintenanceTypeViewController.h"
#import "MaintenanceDetailedViewController.h"
#import "DetailedDocumentViewController.h"

@implementation CircleView

- (id)initWithFrame:(CGRect)frame {
    if ((self = [super initWithFrame:frame])) {
        [self setOpaque:NO];
        [self setBackgroundColor:[UIColor clearColor]];
    }
    return self;
}

- (void)drawRect:(CGRect)rect{
    CGContextRef context= UIGraphicsGetCurrentContext();
    
    CGContextSetFillColorWithColor(context, [UIColor redColor].CGColor);
    
    CGContextSetAlpha(context, 1.0);
    CGContextFillEllipseInRect(context, CGRectMake(0,0,self.frame.size.width,self.frame.size.height));
    
    CGContextSetStrokeColorWithColor(context, [UIColor redColor].CGColor);
    
    CGContextStrokeEllipseInRect(context, CGRectMake(1, 1, self.frame.size.width - 2, self.frame.size.height - 2));
}

@end

@interface DetailedItemViewController ()

@end

static NSMutableDictionary *buildingPermissionDict = nil;

@implementation DetailedItemViewController
@synthesize parent;
@synthesize itemType;
@synthesize itemDetailedDict;
@synthesize detailedInfoController;
@synthesize maintenanceController;
@synthesize lbNotification;
@synthesize cirleNotification;
@synthesize numberUnreadNotification;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil itemType:(int)_itemType parent:(id)_parent
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        dictLanguage = [ApplicationDelegate.arrayLanguage objectAtIndex:0];
        itemType = _itemType;
        parent = _parent;
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    [_leftBackground setBackgroundColor:[UIColor colorWithPatternImage:[UIImage imageNamed:@"grayPattern.png"]]];
    
    _containerView.backgroundColor = [UIColor clearColor];
    _containerView.layer.borderColor = APPLE_BLUE_COLOR.CGColor;
    _containerView.layer.borderWidth = 1;
    
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    
    if (itemType == Building_Type) {
        buildingPermissionDict = [userDefaults objectForKey:BUILDING_PERMISSION];
        
        _lbMainTitle.text = [dictLanguage objectForKey:@"building-mgmt.detailed.main-title"];
        [_btnAIP setTitle:[dictLanguage objectForKey:@"building-mgmt.item.aip"] forState:UIControlStateNormal];
    }
    else {
        buildingPermissionDict = [userDefaults objectForKey:FACILITY_PERMISSION];
        
        _lbMainTitle.text = [dictLanguage objectForKey:@"facility-mgmt.detailed.main-title"];
        [_btnAIP setTitle:[dictLanguage objectForKey:@"facility-mgmt.item.amp"] forState:UIControlStateNormal];
    }
    //get all buttons left from this view, and set isSelected = NO except this one which is selected
    for (UIButton *subviews in self.view.subviews) {
        if ([subviews isKindOfClass:[UIButton class]] && subviews.tag >= 100) {
            //set title adjusts down of button
            subviews.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
            subviews.contentVerticalAlignment   = UIControlContentVerticalAlignmentBottom;
            [subviews setTitleEdgeInsets:UIEdgeInsetsMake(0, 0, 5, 0)];
            
            [subviews setTitleColor:[UIColor darkGrayColor] forState:UIControlStateNormal];
            [subviews setTitleColor:APPLE_BLUE_COLOR forState:UIControlStateSelected];
            
            //set multi line for button title
            subviews.titleLabel.lineBreakMode = NSLineBreakByWordWrapping;
            subviews.titleLabel.textAlignment = NSTextAlignmentCenter;
        }
    }
    
    //set title label text
    [_btnDetailedInfo setTitle:[dictLanguage objectForKey:@"building-mgmt.item.detailed-info"] forState:UIControlStateNormal];
    [_btnMaintenanceMgmt setTitle:[dictLanguage objectForKey:@"building-mgmt.item.maintenance-mgmt"] forState:UIControlStateNormal];
    [_btnDocumentAttachment setTitle:[dictLanguage objectForKey:@"building-mgmt.item.document-attachment"] forState:UIControlStateNormal];
    [_btnNotification setTitle:[dictLanguage objectForKey:@"building-mgmt.item.notification"] forState:UIControlStateNormal];
    
    [self handleMainAction:_btnDetailedInfo];
    currentSelectedTab = detailed_info_tab;
    
    //check expire for item
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"MMM dd, yyyy"];

    NSString *expiredDateStr = [itemDetailedDict objectForKey:@"date_of_exp"];
    
    if (expiredDateStr != Nil && ![expiredDateStr isEqualToString:@""]) {
        NSDate *expiredDate = [dateFormatter dateFromString:expiredDateStr];
        
        NSDate* now = [NSDate date];
        NSDateComponents* ageComponents = [[NSCalendar currentCalendar]
                                           components:NSCalendarUnitDay | NSCalendarUnitMonth | NSCalendarUnitYear
                                           fromDate:now
                                           toDate:expiredDate
                                           options:0];
        NSInteger year  = [ageComponents year];
        NSInteger month = [ageComponents month];
        NSInteger day   = [ageComponents day];
        
        if (year == 0 && month <= 1 && day == 0) {
            numberUnreadNotification += 1;
        }
    }
    
//    [self performSelectorInBackground:@selector(delayToCountNumberUnreadNotification) withObject:self];
    [self performSelector:@selector(delayToCountNumberUnreadNotification) withObject:Nil afterDelay:0.5];
}

- (void) delayToCountNumberUnreadNotification {
    //count number unread scheduling
    numberUnreadNotification = [CouchBaseLiteLib countUnreadSchedulingByItem:itemDetailedDict];

    if (numberUnreadNotification > 0) {
        cirleNotification = [[CircleView alloc] initWithFrame:CGRectMake(70, 10, 25, 25)];
        [_btnNotification addSubview:cirleNotification];
        
        lbNotification = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 25, 25)];
        lbNotification.font = [UIFont systemFontOfSize:13];
        lbNotification.textAlignment = NSTextAlignmentCenter;
        lbNotification.textColor = [UIColor whiteColor];
        lbNotification.backgroundColor = [UIColor clearColor];
        lbNotification.text = [NSString stringWithFormat:@"%d",numberUnreadNotification];
        [cirleNotification addSubview:lbNotification];
    }
}

- (void) setNotificationAlert:(int)_numberUnreadNotification {
    numberUnreadNotification = _numberUnreadNotification;
    if (numberUnreadNotification > 0) {
        cirleNotification.hidden = lbNotification.hidden = NO;
        lbNotification.text = [NSString stringWithFormat:@"%d",numberUnreadNotification];
    }
    else {
        cirleNotification.hidden = lbNotification.hidden = YES;
    }
}

- (IBAction)backPreviousView:(id)sender {
    [self.navigationController popViewControllerAnimated:YES];
}

- (IBAction)tapRightCornerButton:(id)sender {
    if (currentSelectedTab == detailed_info_tab) {
        //Get permission about this tab
        NSMutableDictionary *permissionDict = [buildingPermissionDict objectForKey:@"detailsInfo"];
        BOOL isEditable = [[permissionDict objectForKey:@"update"] boolValue];
        if (!isEditable) {
            UIAlertView *dialog = [[UIAlertView alloc] initWithTitle:[dictLanguage objectForKey:@"general.warning"] message:[dictLanguage objectForKey:@"general.permission.no-right-access"] delegate:nil cancelButtonTitle:[dictLanguage objectForKey:@"general.ok"] otherButtonTitles:nil];
            [dialog show];
            return;
        }
        
        AddNewItemViewController *controller = [[AddNewItemViewController alloc] initWithNibName:@"AddNewItemViewController" bundle:nil itemType:itemType parent:self];
        controller.isEdit = YES;
        controller.itemDetailedDict = itemDetailedDict;
        [self.navigationController pushViewController:controller animated:YES];
    }
    else if (currentSelectedTab == aip_tab) {
        //Get permission about this tab
        NSMutableDictionary *permissionDict;
        
        NSString *strCategory;
        int maintenanceType = 0;
        if (itemType == Building_Type) {
            permissionDict = [buildingPermissionDict objectForKey:@"aip"];
            
            strCategory = [dictLanguage objectForKey:@"maintenance-mgmt.service-type.inspection"];
        }
        else
        {
            permissionDict = [buildingPermissionDict objectForKey:@"amp"];
            
            strCategory = [dictLanguage objectForKey:@"maintenance-mgmt.service-type.maintenance"];
            maintenanceType = 0;
        }
        
        BOOL isEditable = [[permissionDict objectForKey:@"update"] boolValue];
        if (!isEditable) {
            UIAlertView *dialog = [[UIAlertView alloc] initWithTitle:[dictLanguage objectForKey:@"general.warning"] message:[dictLanguage objectForKey:@"general.permission.no-right-access"] delegate:nil cancelButtonTitle:[dictLanguage objectForKey:@"general.ok"] otherButtonTitles:nil];
            [dialog show];
            return;
        }
        
//        NSDate *today = [NSDate date];
//        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
//        [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
//        NSString *todayStr = [dateFormatter stringFromDate:today];
        
        NSMutableDictionary *dictSchedule = [NSMutableDictionary dictionaryWithObjectsAndKeys:strCategory,@"scheduleCategory",[itemDetailedDict objectForKey:@"service"],@"service",[itemDetailedDict objectForKey:@"camp"],@"camp",[itemDetailedDict objectForKey:@"unit"],@"unit",[itemDetailedDict objectForKey:@"building"],@"building",[itemDetailedDict objectForKey:@"floor"],@"floor",@"",@"startDate",@"",@"lastUpdate",@"",@"reMark",[NSNumber numberWithInt:maintenanceType],@"maintenanceTypeId",[NSNumber numberWithInt:itemType],@"itemType",[NSNumber numberWithInt:0],@"categoryTypeId",nil];
        if (itemType == Facility_Type)
        {
            [dictSchedule setObject:[itemDetailedDict objectForKey:@"room"] forKey:@"room"];
            [dictSchedule setObject:[NSNumber numberWithInt:Schedule_AMP_Mgmt_Type] forKey:SCHEDULE_MGMT_TYPE];
        }
        
        else
        {
            [dictSchedule setObject:[itemDetailedDict objectForKey:@"item_name"] forKey:@"room"];
            [dictSchedule setObject:[NSNumber numberWithInt:Schedule_AIP_Mgmt_Type] forKey:SCHEDULE_MGMT_TYPE];
        }
        
        if ([[dictSchedule objectForKey:@"scheduleCategory"] isEqualToString:[dictLanguage objectForKey:@"maintenance-mgmt.service-type.inspection"]]) {
            [dictSchedule setObject:[NSNumber numberWithInt:Inspection] forKey:@"categoryId"];
        }
        else
            [dictSchedule setObject:[NSNumber numberWithInt:Maintenance] forKey:@"categoryId"];
        [dictSchedule setObject:[itemDetailedDict objectForKey:@"_id"] forKey:@"itemId"];
        NSMutableDictionary *firstItem = [aipController getFirstItem];
        if (firstItem == nil)
            ;
        else if([firstItem objectForKey:@"startDate"] && ![[firstItem objectForKey:@"startDate"] isEqualToString:@""])
            [dictSchedule setObject:[firstItem objectForKey:@"startDate"] forKey:@"lastUpdate"];
        ScheduleInspectionViewController *controller = [[ScheduleInspectionViewController alloc] initWithNibName:@"ScheduleInspectionViewController" bundle:[NSBundle mainBundle] schedule:dictSchedule];
        controller.delegate = self;
        [self.navigationController pushViewController:controller animated:YES];
        [controller reloadInfoSchedule];
    }
    else if (currentSelectedTab == maintenance_tab) {
        //Get permission about this tab
        NSMutableDictionary *permissionDict = [buildingPermissionDict objectForKey:@"maintenanceManagement"];
        BOOL isEditable = [[permissionDict objectForKey:@"update"] boolValue];
        if (!isEditable) {
            UIAlertView *dialog = [[UIAlertView alloc] initWithTitle:[dictLanguage objectForKey:@"general.warning"] message:[dictLanguage objectForKey:@"general.permission.no-right-access"] delegate:nil cancelButtonTitle:[dictLanguage objectForKey:@"general.ok"] otherButtonTitles:nil];
            [dialog show];
            return;
        }
        
        MaintenanceTypeViewController *controller = [[MaintenanceTypeViewController alloc] initWithNibName:@"MaintenanceTypeViewController" bundle:nil serviceType:Inspection parent:self];
        UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController:controller];
        navController.modalPresentationStyle = UIModalPresentationPageSheet;
        [self presentModalViewController:navController animated:YES];
        
        if (SYSTEM_VERSION_LESS_THAN(@"7.0"))
            navController.view.superview.frame = CGRectMake(300, 100, 400, 400);
    }
}

- (IBAction)handleMainAction:(UIButton *)sender {
    //get all buttons left from this view, and set isSelected = NO except this one which is selected
    for (UIButton *subviews in self.view.subviews) {
        if ([subviews isKindOfClass:[UIButton class]] && subviews.tag >= 100) {
            [subviews setSelected:NO];
        }
    }
    [sender setSelected:YES];
    currentSelectedTab = sender.tag;
    
    switch (currentSelectedTab) {
        case detailed_info_tab:
        {
            //Get permission about this tab
            NSMutableDictionary *permissionDict = [buildingPermissionDict objectForKey:@"detailsInfo"];
            BOOL isAccess = [[permissionDict objectForKey:@"access"] boolValue];
            if (!isAccess) {
                UIAlertView *dialog = [[UIAlertView alloc] initWithTitle:[dictLanguage objectForKey:@"general.warning"] message:[dictLanguage objectForKey:@"general.permission.no-right-access"] delegate:nil cancelButtonTitle:[dictLanguage objectForKey:@"general.ok"] otherButtonTitles:nil];
                [dialog show];
                return;
            }
            
            _btnRightCorner.hidden = NO;
            //set right corner button background image
            [_btnRightCorner setBackgroundImage:[UIImage imageNamed:@"btnEdit.png"] forState:UIControlStateNormal];
            
            if (detailedInfoController == nil) {
                detailedInfoController = [[DetailedInfoViewController alloc] initWithNibName:@"DetailedInfoViewController" bundle:nil itemType:itemType parent:self];
                detailedInfoController.itemDetailedDict = itemDetailedDict;
                [_containerView addSubview:detailedInfoController.view];
            }
            
            detailedInfoController.view.hidden = NO;
            aipController.view.hidden = YES;
            maintenanceController.view.hidden = YES;
            notificationController.view.hidden = YES;
            documentController.view.hidden = YES;
            break;
        }
        case aip_tab:
        {
            //Get permission about this tab
            NSMutableDictionary *permissionDict;
            if (itemType == Building_Type) {
                permissionDict = [buildingPermissionDict objectForKey:@"aip"];
            }
            else
            {
                permissionDict = [buildingPermissionDict objectForKey:@"amp"];
            }

            BOOL isAccess = [[permissionDict objectForKey:@"access"] boolValue];
            if (!isAccess) {
                UIAlertView *dialog = [[UIAlertView alloc] initWithTitle:[dictLanguage objectForKey:@"general.warning"] message:[dictLanguage objectForKey:@"general.permission.no-right-access"] delegate:nil cancelButtonTitle:[dictLanguage objectForKey:@"general.ok"] otherButtonTitles:nil];
                [dialog show];
                
                //back to detail info tab
                [self handleMainAction:_btnDetailedInfo];
                
                return;
            }
            
            _btnRightCorner.hidden = NO;
            [_btnRightCorner setBackgroundImage:[UIImage imageNamed:@"btnAddNew.png"] forState:UIControlStateNormal];
            
            if (aipController == nil) {
                aipController = [[AIPViewController alloc] initWithNibName:@"AIPViewController" bundle:nil itemType:itemType];
                aipController.itemDetailedDict = itemDetailedDict;
                [_containerView addSubview:aipController.view];
            }
            aipController.delegate = self;
            detailedInfoController.view.hidden = YES;
            aipController.view.hidden = NO;
            maintenanceController.view.hidden = YES;
            notificationController.view.hidden = YES;
            documentController.view.hidden = YES;
            break;
        }
        case maintenance_tab:
        {
            //Get permission about this tab
            NSMutableDictionary *permissionDict = [buildingPermissionDict objectForKey:@"maintenanceManagement"];
            BOOL isAccess = [[permissionDict objectForKey:@"access"] boolValue];
            if (!isAccess) {
                UIAlertView *dialog = [[UIAlertView alloc] initWithTitle:[dictLanguage objectForKey:@"general.warning"] message:[dictLanguage objectForKey:@"general.permission.no-right-access"] delegate:nil cancelButtonTitle:[dictLanguage objectForKey:@"general.ok"] otherButtonTitles:nil];
                [dialog show];
                
                //back to detail info tab
                [self handleMainAction:_btnDetailedInfo];
                
                return;
            }

            _btnRightCorner.hidden = NO;
            [_btnRightCorner setBackgroundImage:[UIImage imageNamed:@"btnAddNew.png"] forState:UIControlStateNormal];
            
            if (maintenanceController == nil) {
                maintenanceController = [[MaintenanceViewController alloc] initWithNibName:@"MaintenanceViewController" bundle:nil itemType:itemType parent:self];
                [_containerView addSubview:maintenanceController.view];
            }
            
            detailedInfoController.view.hidden = YES;
            aipController.view.hidden = YES;
            maintenanceController.view.hidden = NO;
            notificationController.view.hidden = YES;
            documentController.view.hidden = YES;
            break;
        }
        case notification_tab:
        {
            //Get permission about this tab
            NSMutableDictionary *permissionDict = [buildingPermissionDict objectForKey:@"notification"];
            BOOL isAccess = [[permissionDict objectForKey:@"access"] boolValue];
            if (!isAccess) {
                UIAlertView *dialog = [[UIAlertView alloc] initWithTitle:[dictLanguage objectForKey:@"general.warning"] message:[dictLanguage objectForKey:@"general.permission.no-right-access"] delegate:nil cancelButtonTitle:[dictLanguage objectForKey:@"general.ok"] otherButtonTitles:nil];
                [dialog show];
                
                //back to detail info tab
                [self handleMainAction:_btnDetailedInfo];
                
                return;
            }
            
            _btnRightCorner.hidden = YES;
            
            if (notificationController == nil) {
                notificationController = [[NotificationViewController alloc] initWithNibName:@"NotificationViewController" bundle:nil itemType:itemType parent:self];
                [_containerView addSubview:notificationController.view];
            }
            
            detailedInfoController.view.hidden = YES;
            aipController.view.hidden = YES;
            maintenanceController.view.hidden = YES;
            notificationController.view.hidden = NO;
            documentController.view.hidden = YES;
            break;
        }
        case document_attachment_tab:
        {
            //Get permission about this tab
            NSMutableDictionary *permissionDict = [buildingPermissionDict objectForKey:@"documentAttachment"];
            BOOL isAccess = [[permissionDict objectForKey:@"access"] boolValue];
            if (!isAccess) {
                UIAlertView *dialog = [[UIAlertView alloc] initWithTitle:[dictLanguage objectForKey:@"general.warning"] message:[dictLanguage objectForKey:@"general.permission.no-right-access"] delegate:nil cancelButtonTitle:[dictLanguage objectForKey:@"general.ok"] otherButtonTitles:nil];
                [dialog show];
                
                //back to detail info tab
                [self handleMainAction:_btnDetailedInfo];
                
                return;
            }
            
            _btnRightCorner.hidden = YES;
            
            if (documentController == nil) {
                documentController = [[DocumentViewController alloc] initWithNibName:@"DocumentViewController" bundle:nil itemType:itemType parent:self];
                [_containerView addSubview:documentController.view];
            }
            
            detailedInfoController.view.hidden = YES;
            aipController.view.hidden = YES;
            maintenanceController.view.hidden = YES;
            notificationController.view.hidden = YES;
            documentController.view.hidden = NO;
            break;
        }
        default:
            break;
    }
}

- (void) confirmSelectType:(NSMutableDictionary*)dict {
    //save current selected service type
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    [userDefaults setObject:[dict objectForKey:@"serviceType"] forKey:SELECTED_SERVICE_TYPE];
    
//    BuildingMgmtViewController *controller = [[BuildingMgmtViewController alloc] initWithNibName:@"BuildingMgmtViewController" bundle:nil itemType:itemType];
//    controller.parent = self;
//    controller.serviceType = [[dict objectForKey:@"serviceType"] intValue];
//    
//    [self.navigationController pushViewController:controller animated:NO];
    
    
    //if serviceType = Maintenance, display tableview to list maintenance type
    int serviceType = [[dict objectForKey:@"serviceType"] intValue];
    if (serviceType == Maintenance){
        MaintenanceTypeViewController *controller = [[MaintenanceTypeViewController alloc] initWithNibName:@"MaintenanceTypeViewController" bundle:nil serviceType:Maintenance parent:self];
        NSMutableDictionary *tmpDict = [detailedInfoController.itemDetailedDict mutableCopy];
        [tmpDict setObject:[detailedInfoController.itemDetailedDict objectForKey:@"_id"] forKey:@"itemId"];
        controller.itemDetailedDict = tmpDict;
        controller.itemType = itemType;
        UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController:controller];
        navController.modalPresentationStyle = UIModalPresentationPageSheet;
        [self presentModalViewController:navController animated:YES];
        
        if (SYSTEM_VERSION_LESS_THAN(@"7.0"))
            navController.view.superview.frame = CGRectMake(300, 100, 400, 400);
    }
    else {
        NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
        NSString *userId = [userDefaults objectForKey:ACCOUNT_ID];
        //create temporary inspection
        NSMutableDictionary *inputInspectionDict = [NSMutableDictionary dictionaryWithObjectsAndKeys:InspectionDoc,@"Table",userId,@"userId", nil];
        NSError *error;
        if ([[CouchBaseLiteLib sharedCouchBaseLite] createDocument:inputInspectionDict error:&error]) {
            MaintenanceDetailedViewController *controller = [[MaintenanceDetailedViewController alloc] initWithNibName:@"MaintenanceDetailedViewController" bundle:nil parent:self serviceType:Inspection];
            controller.itemDetailDict = detailedInfoController.itemDetailedDict;
            controller.itemType = itemType;
            controller.inputInspectionDict = inputInspectionDict;
            [self.navigationController pushViewController:controller animated:YES];
        }
    }
}

- (void)refreshListSchedule{
    if (currentSelectedTab == aip_tab) {
        [aipController reloadListSchedule];
    }
    else if (currentSelectedTab == notification_tab) {
        [notificationController listSchedule];
        [self setNotificationAlert:numberUnreadNotification+1];
    }
}
- (void) selectDetailedMaintenance:(NSMutableDictionary*)dict {
    NSString *table = [dict objectForKey:@"Table"];
    
    if ([table isEqualToString:InspectionDoc]) {
        MaintenanceDetailedViewController *controller = [[MaintenanceDetailedViewController alloc] initWithNibName:@"MaintenanceDetailedViewController" bundle:nil parent:self serviceType:Inspection];
        controller.isEdit = YES;
        controller.itemDetailDict = dict;
        
        //get item document (room/equipment)
        CBLDocument *itemDoc = [CouchBaseLiteLib getDocumentById:[dict objectForKey:@"itemId"]];
        NSMutableDictionary *itemDict = [itemDoc.properties mutableCopy];
        
        [controller.itemDetailDict setObject:[itemDict objectForKey:@"item_name"] forKey:@"item_name"];
        [controller.itemDetailDict setObject:[itemDict objectForKey:@"building"] forKey:@"building"];
        [controller.itemDetailDict setObject:[itemDict objectForKey:@"camp"] forKey:@"camp"];
        [controller.itemDetailDict setObject:[itemDict objectForKey:@"floor"] forKey:@"floor"];
        [controller.itemDetailDict setObject:[itemDict objectForKey:@"service"] forKey:@"service"];
        [controller.itemDetailDict setObject:[itemDict objectForKey:@"unit"] forKey:@"unit"];
        [controller.itemDetailDict setObject:[itemDict objectForKey:@"Table"] forKey:@"Table"];
        
        NSString *room = [itemDict objectForKey:@"room"] == nil ? @"":[itemDict objectForKey:@"room"];
        NSString *description = [itemDict objectForKey:@"description"] == nil ? @"":[itemDict objectForKey:@"description"];
        NSString *system = [itemDict objectForKey:@"system"] == nil ? @"":[itemDict objectForKey:@"system"];
        
        [controller.itemDetailDict setObject:room forKey:@"room"];
        [controller.itemDetailDict setObject:description forKey:@"description"];
        [controller.itemDetailDict setObject:system forKey:@"system"];
        [controller.itemDetailDict setObject:@"" forKey:@"itemType"];
        
        [self.navigationController pushViewController:controller animated:YES];
    }
    else {
        MaintenanceDetailedViewController *controller = [[MaintenanceDetailedViewController alloc] initWithNibName:@"MaintenanceDetailedViewController" bundle:nil parent:self serviceType:Maintenance];
        controller.isEdit = YES;
        
        int maintenanceType = [[dict objectForKey:@"maintenanceTypeId"] intValue];
        NSString *maintenanceName = [ApplicationDelegate getMaintenanceName:maintenanceType];
        
        //set current maitenance selected type
        NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
        [userDefaults setObject:[NSNumber numberWithInt:maintenanceType] forKey:CURRENT_SELECTED_MAINTENANCE_TYPE];
        
        controller.itemDetailDict = dict;
        [controller.itemDetailDict setObject:[dict objectForKey:@"maintenanceTypeId"] forKey:@"itemType"];
        [controller.itemDetailDict setObject:maintenanceName forKey:@"itemName"];
        [self.navigationController pushViewController:controller animated:YES];
        [self performSelector:@selector(delayForPushingView) withObject:nil afterDelay:0.2];
        
    }
}

- (void) delayForPushingView {
    MaintenanceDetailedViewController *controller = [self.navigationController.viewControllers lastObject];
    [controller confirmMaintenanceType:controller.itemDetailDict itemDetailedDict:controller.itemDetailDict];
}

- (void) confirmSelectMaintenance:(NSMutableDictionary*)_dict itemDetailedDict:(NSMutableDictionary*)_itemDetailedDict {
    //if add new maintenance, set isInspectionFailed = NO
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    [userDefaults setObject:[NSNumber numberWithBool:NO] forKey:IS_INSPECTION_FAILED];
    
    MaintenanceDetailedViewController *controller = [[MaintenanceDetailedViewController alloc] initWithNibName:@"MaintenanceDetailedViewController" bundle:nil parent:self serviceType:Maintenance];
    controller.itemDetailDict = _itemDetailedDict;
    controller.itemType = itemType;
    [self.navigationController pushViewController:controller animated:YES];
    
    [self performSelector:@selector(delayToSelectMaintenance:) withObject:_dict afterDelay:0.5];
}

- (void) delayToSelectMaintenance:(NSMutableDictionary*)_dict {
    //get the last controller
    MaintenanceDetailedViewController *controller = [[self.navigationController viewControllers] lastObject];
    
    NSMutableDictionary *tmpDict = [controller.itemDetailDict mutableCopy];
    [tmpDict setObject:[_dict objectForKey:@"itemType"] forKey:@"maintenanceTypeId"];
    [controller confirmMaintenanceType:_dict itemDetailedDict:tmpDict];
}

- (void) selectDetailedNotification:(NSMutableDictionary*)_dict {
    ScheduleInspectionViewController *controller = [[ScheduleInspectionViewController alloc] initWithNibName:@"ScheduleInspectionViewController" bundle:[NSBundle mainBundle] schedule:_dict];
    controller.isEditting = YES;
    controller.delegate = self;
    [self.navigationController pushViewController:controller animated:YES];
}

- (void) selectDetailedDocument:(AsynImageButton*)sender {
    DetailedDocumentViewController *controller = [[DetailedDocumentViewController alloc] initWithNibName:@"DetailedDocumentViewController" bundle:nil itemType:itemType parent:documentController];
    UINavigationController *naviController = [[UINavigationController alloc] initWithRootViewController:controller];
    
    CBLDocument *document = [[CouchBaseLiteLib sharedCouchBaseLite] getDocumentById:[sender.dataDict objectForKey:@"_id"]];
    NSData *imageData = nil;
    if (document.currentRevision) {
        CBLAttachment *attach = [document.currentRevision attachmentNamed:[sender.dataDict objectForKey:@"fileName"]];
        imageData = [attach body];
        controller.documentImage = [UIImage imageWithData:imageData];
        controller.documentDict  = sender.dataDict;
        [self presentViewController:naviController animated:YES completion:nil];
    }
}

@end
